package com.tt.vtg.controller;

import com.tt.vtg.utils.VtgUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import org.apache.commons.lang.StringUtils;

import com.tt.vtg.dao.entity.User;

import java.util.Date;
import java.util.List;
import com.tt.vtg.plain.info.UserInfo;
import com.tt.vtg.service.UserService;

@RestController
public class UserManagementController {
	
	@Autowired
	@Qualifier("userSvc")
	private UserService userSvc;
	
	@RequestMapping(value="/user", method=RequestMethod.POST)
	@ResponseStatus(value = HttpStatus.CREATED)
	public long createUser(@RequestBody User u){
		
		u.setCreateTime(new Date());
		String salt = VtgUtils.generateSalt();
		u.setPassword(VtgUtils.encrypt(u.getPassword() + salt));
		u.setSalt(salt);
		userSvc.save(u);
		long id = getUser(u.getUserId()).getId();
		
		return id;
	}
	
	@RequestMapping(value="/user/{userId}", method=RequestMethod.GET)
	public User getUser(@PathVariable("userId") String userId){
		
		User user = userSvc.getUserEntityById(userId).get();
		
		return user;
	}
	
	@RequestMapping(value = "/users", method=RequestMethod.GET)
	public List<UserInfo> getUsers(){
		
		List<UserInfo> users = userSvc.getAll();

		return users;
	}
	
	@RequestMapping(value="/user/{userId}", method=RequestMethod.DELETE)
	@ResponseStatus(value = HttpStatus.NO_CONTENT)
	public void deleteUser(@PathVariable("userId") String userId){
		
		User user = getUser(userId);
		userSvc.delete(user.getId());

	}
	
	@RequestMapping(value="/user/{userId}", method=RequestMethod.PUT)
	@ResponseStatus(value = HttpStatus.NO_CONTENT)
	public void updateUser(@RequestBody User u, @PathVariable("userId") String userId){
		
		User user = getUser(userId);

		updateUserInfo(u, user);
		
		userSvc.update(user);
	}

	private void updateUserInfo(User userInDB, User userInRequest) {
		if(StringUtils.isNotEmpty(userInDB.getEmail())) {
			userInRequest.setEmail(userInDB.getEmail());
		}
		
		if(StringUtils.isNotEmpty(userInDB.getUserName())) {
			userInRequest.setUserName(userInDB.getUserName());
		}
		
		if(StringUtils.isNotEmpty(userInDB.getSalt())) {
			userInRequest.setSalt(userInDB.getSalt());
		}
		
		if(StringUtils.isNotEmpty(userInDB.getPassword())) {
			userInRequest.setPassword(userInDB.getPassword());
		}
	}
	
}
